#!/usr/bin/env python
# -*- coding:utf8 -*-
# uncompyle6 version 2.15.1
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.10 (default, Jul  1 2017, 13:36:56) 
# [GCC 4.4.6 20110731 (Red Hat 4.4.6-4)]
# Embedded file name: ./paas/engine/views.py
# Compiled at: 2017-11-16 15:44:28
"""
Tencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
"""
import json, re
from django.conf import settings
from common.decorators import is_superuser
from common.mymako import render_mako_context, render_json
from common.log import logger
from engine.api import get_anget_healthz, check_services_status
from engine.models import BkServer, ThirdServer, THIRD_SERVER_CATEGORY_CHOICES

@is_superuser
def servers(request):
    """
    AppServer信息页面
    """
    servers = BkServer.objects.all()
    engine_host = settings.ENGINE_HOST
    paas_domain = settings.PAAS_DOMAIN
    domain_parts = paas_domain.split(':') if paas_domain else [paas_domain]
    if len(domain_parts) == 2:
        paas_domain_host, paas_domain_port = domain_parts
    else:
        paas_domain_host = paas_domain
        paas_domain_port = 80
    return render_mako_context(request, 'engine/servers.html', {'servers': servers,'engine_host': engine_host,
       'paas_domain': paas_domain,
       'paas_domain_host': paas_domain_host,
       'paas_domain_port': paas_domain_port
       })


@is_superuser
def add_server_info(request):
    """
    添加\编辑AppServer信息
    """
    server_id = request.POST.get('server_id', '')
    server_ip = request.POST.get('server_ip', '')
    server_port = request.POST.get('server_port', '')
    app_port = request.POST.get('app_port', '')
    server_cate = request.POST.get('server_cate', '')
    ip_pattarn = re.compile('^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$')
    if not ip_pattarn.match(server_ip):
        return render_json({'result': False,'msg': u'服务器IP格式不正确','data': {}})
    if not server_port:
        return render_json({'result': False,'msg': u'Agent端口不能为空','data': {}})
    try:
        server_port = int(server_port)
    except:
        return render_json({'result': False,'msg': u'Agent端口必须为正数','data': {}})

    if not app_port:
        return render_json({'result': False,'msg': u'App服务端口不能为空','data': {}})
    try:
        app_port = int(app_port)
    except:
        return render_json({'result': False,'msg': u'App服务端口必须为正数','data': {}})

    if not server_cate:
        return render_json({'result': False,'msg': u'服务器类别不能为空','data': {}})
    if server_id:
        bkservers = BkServer.objects.exclude(id=server_id)
    else:
        bkservers = BkServer.objects.all()
    server_count = bkservers.filter(ip_address=server_ip, ip_port=server_port).count()
    if server_count > 0:
        msg = (u'IP为[{ip}], 端口为 [{port}] 的服务器已经存在').format(ip=server_ip, port=server_port)
        return render_json({'result': False,'msg': msg})
    if server_id:
        BkServer.objects.filter(id=server_id).update(ip_address=server_ip, ip_port=server_port, app_port=app_port, category=server_cate)
        data = {}
    else:
        try:
            server = BkServer.objects.create(ip_address=server_ip, ip_port=server_port, app_port=app_port, category=server_cate, is_active=False)
            data = {'server_id': server.id,
               's_id': str(server.s_id),
               'token': str(server.token)
               }
        except Exception as e:
            logger.exception(u'保存应用服务器信息异常:%s' % e)
            return render_json({'result': False,'msg': u'保存出错','data': {}})

    return render_json({'result': True,'msg': u'保存成功','data': data})


@is_superuser
def del_server_info(request):
    """
    删除AppServer信息
    """
    server_id = request.POST.get('server_id', '')
    if not server_id:
        return render_json({'result': False,'msg': u'请选择要删除的服务器'})
    try:
        BkServer.objects.filter(id=server_id).delete()
    except Exception:
        logger.exception(u'删除服务器[id:%s]失败' % server_id)
        return render_json({'result': False,'msg': u'删除服务器失败'})

    return render_json({'result': True,'msg': u'删除成功'})


@is_superuser
def active_server(request):
    """
    激活服务器
    """
    server_id = request.POST.get('server_id', '')
    try:
        server = BkServer.objects.get(id=server_id)
    except:
        logger.exception(u'服务器信息[id:%s]不存在' % server_id)
        return render_json({'result': False,'msg': u'服务器信息不存在,请重新添加'})

    if server.is_active:
        return render_json({'result': True,'msg': u'服务器已激活'})
    server_category = server.category
    active_servers = BkServer.objects.exclude(id=server_id).filter(category=server_category, is_active=True)
    if active_servers.exists():
        active_server_ip = active_servers[0].ip_address
        active_server_port = active_servers[0].ip_port
        active_server_cate = active_servers[0].get_category_display()
        return render_json({'result': False,'msg': u'已经有一台%s [IP:%s, 端口:%s] 被激活<br><br>不能再激活其他%s' % (
                 active_server_cate, active_server_ip, active_server_port, active_server_cate)
           })
    is_success, agents = get_anget_healthz(server_id)
    if not is_success or not isinstance(agents, dict):
        return render_json({'result': False,'msg': u'检测Agent信息时出错,可能原因:App Engine 未正常启动'})
    s_id = str(server.s_id)
    if s_id not in agents.keys():
        return render_json({'result': False,'msg': u'服务器上未安装Agent, 请安装Agent后重试'})
    agent_data = agents.get(s_id, {})
    agent_code = agent_data.get('code', '')
    if agent_code != 0:
        msg = u'PaasAgent未正常启动,您可能:<br><br>1) 未安装PaasAgent, 请按使用说明安装Agent后重试<br><br>2) PaasAgent未正常启动, 请查看PaasAgent日志排查<br><br>日志默认在 ${AGENT_ROOT}/logs/paasagent/agent.log'
        return render_json({'result': False,'msg': msg})
    server_mac = agent_data.get('mac', '')
    server.is_active = True
    server.mac = server_mac
    server.save()
    return render_json({'result': True,'msg': u'服务器已激活'})


@is_superuser
def refresh_server(request):
    """
    刷新agent服务器状态
    """
    server_id = request.POST.get('server_id', '')
    try:
        server = BkServer.objects.get(id=server_id)
    except:
        logger.exception(u'服务器信息[id:%s]不存在' % server_id)
        return render_json({'result': False,'msg': u'服务器信息不存在,请重新添加'})

    is_success, agents = get_anget_healthz(server_id)
    s_id = str(server.s_id)
    if is_success and isinstance(agents, dict):
        agent_data = agents.get(s_id, {})
        agent_code = agent_data.get('code', '')
        if agent_code == 0:
            agent_msg = u'服务器已激活'
        else:
            agent_msg = u'检测到服务器状态异常,您可能:<br><br>1) 未安装PaasAgent, 请按使用说明安装Agent后重试<br><br>2) PaasAgent未正常启动, 请查看PaasAgent日志排查<br><br>日志默认在 ${AGENT_ROOT}/logs/paasagent/agent.log'
        server.is_active = True if agent_code == 0 else False
        server.save()
        return render_json({'result': True,'code': agent_code,'msg': agent_msg})
    return render_json({'result': False,'msg': u'刷新Agent信息时出错,可能原因:App Engine 未正常启动'})


@is_superuser
def third_servers(request):
    servers = ThirdServer.objects.all()
    return render_mako_context(request, 'engine/third_servers.html', {'servers': servers,'third_cates': THIRD_SERVER_CATEGORY_CHOICES})


@is_superuser
def add_third_server_info(request):
    """
    添加\编辑第三方服务信息
    """
    server_id = request.POST.get('server_id', '')
    server_ip = request.POST.get('server_ip', '')
    server_port = request.POST.get('server_port', '')
    server_cate = request.POST.get('server_cate', '')
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')
    ip_pattarn = re.compile('^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$')
    if not ip_pattarn.match(server_ip):
        return render_json({'result': False,'msg': u'服务器IP格式不正确','data': {}})
    if not server_port:
        return render_json({'result': False,'msg': u'端口不能为空','data': {}})
    try:
        server_port = int(server_port)
    except:
        return render_json({'result': False,'msg': u'端口必须为正数','data': {}})

    if not username:
        return render_json({'result': False,'msg': u'用户名不能为空','data': {}})
    if not password:
        return render_json({'result': False,'msg': u'密码不能为空','data': {}})
    if not server_cate:
        return render_json({'result': False,'msg': u'服务器类型不能为空','data': {}})
    if server_id:
        servers = ThirdServer.objects.exclude(id=server_id)
    else:
        servers = ThirdServer.objects.all()
    for _s in servers:
        if _s.ip_address == server_ip and _s.ip_port == server_port:
            msg = (u'IP为[{ip}], 端口为 [{port}] 的服务器已经存在').format(ip=server_ip, port=server_port)
            return render_json({'result': False,'msg': msg})

    server_info = {'ip_address': server_ip,
       'ip_port': server_port,
       'username': username,
       'password': password
       }
    server_info = json.dumps(server_info)
    if server_id:
        ThirdServer.objects.filter(id=server_id).update(server_info=server_info, category=server_cate)
        data = {}
    else:
        try:
            server = ThirdServer.objects.create(server_info=server_info, category=server_cate, is_active=False)
            data = {'server_id': server.id
               }
        except Exception as e:
            logger.exception(u'保存服务信息异常:%s' % e)
            return render_json({'result': False,'msg': u'保存出错','data': {}})

    return render_json({'result': True,'msg': u'保存成功','data': data})


@is_superuser
def del_third_server_info(request):
    """
    删除第三方服务
    """
    server_id = request.POST.get('server_id', '')
    if not server_id:
        return render_json({'result': False,'msg': u'请选择要删除的服务'})
    try:
        ThirdServer.objects.filter(id=server_id).delete()
    except Exception:
        logger.exception(u'删除服务[id:%s]失败' % server_id)
        return render_json({'result': False,'msg': u'删除服务失败'})

    return render_json({'result': True,'msg': u'删除成功'})


@is_superuser
def active_third_server(request):
    """
    激活第三方服务
    """
    server_id = request.POST.get('server_id', '')
    try:
        server = ThirdServer.objects.get(id=server_id)
    except:
        logger.exception(u'服务信息[id:%s]不存在' % server_id)
        return render_json({'result': False,'msg': u'服务信息不存在,请重新添加'})

    if server.is_active:
        return render_json({'result': True,'msg': u'服务已激活'})
    server_category = server.category
    active_servers = ThirdServer.objects.exclude(id=server_id).filter(category=server_category, is_active=True)
    if active_servers.exists():
        active_server_cate = active_servers[0].get_category_display()
        return render_json({'result': False,'msg': u'已经有一台 %s 服务被激活<br><br>不能再激活其他 %s 服务' % (
                 active_server_cate, active_server_cate)
           })
    is_success, res_data = check_services_status(server_category, server_id)
    if not is_success or not isinstance(res_data, dict):
        return render_json({'result': False,'msg': u'检测服务信息时出错,可能原因:App Engine 未正常启动'})
    if res_data.get('code', '') != 0:
        msg = res_data.get('msg', '')
        return render_json({'result': False,'msg': msg})
    server.is_active = True
    server.save()
    return render_json({'result': True,'msg': u'服务已激活'})


@is_superuser
def refresh_third_server(request):
    """
    刷新agent服务器状态
    """
    server_id = request.POST.get('server_id', '')
    try:
        server = ThirdServer.objects.get(id=server_id)
        server_category = server.category
    except:
        logger.exception(u'服务器信息[id:%s]不存在' % server_id)
        return render_json({'result': False,'msg': u'服务器信息不存在,请重新添加'})

    is_success, res_data = check_services_status(server_category, server_id)
    if is_success and isinstance(res_data, dict):
        server_code = res_data.get('code', '')
        if server_code == 0:
            msg = u'服务已激活'
        else:
            msg = res_data.get('msg', u'检测到服务状态异常')
        server.is_active = True if server_code == 0 else False
        server.save()
        return render_json({'result': True,'code': server_code,'msg': msg})
    return render_json({'result': False,'msg': u'刷新服务信息时出错,可能原因:App Engine 未正常启动'})
